package dev.alm.persistencedemo.config;

import dev.alm.persistencedemo.component.RedisChatMemoryStore;
import dev.alm.persistencedemo.service.ChatService;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LLMConfig {

    @Value("${llm.api.key}")
    private String apiKey;

    @Value("${llm.model.name}")
    private String modelName;

    @Value("${llm.base.url}")
    private String baseUrl;

    @Resource
    private RedisChatMemoryStore redisChatMemoryStore;

    @Bean
    public OpenAiStreamingChatModel openAiStreamingChatModel() {
        return OpenAiStreamingChatModel.builder()
                .apiKey(apiKey)
                .modelName(modelName)
                .baseUrl(baseUrl)
                .build();
    }

    @Bean
    public ChatService chatService(OpenAiStreamingChatModel openAiStreamingChatModel) {
        ChatMemoryProvider chatMemoryProvider = memoryId -> MessageWindowChatMemory.builder()
                .id(memoryId)
                .maxMessages(100)
                .chatMemoryStore(redisChatMemoryStore)
                .build();
        return AiServices.builder(ChatService.class)
                .streamingChatModel(openAiStreamingChatModel)
                .chatMemoryProvider(chatMemoryProvider)
                .build();
    }

}
